package org.sraosha.microservice.oauth2.service.impl;

import org.sraosha.microservice.oauth2.mapper.UserMapper;
import org.sraosha.microservice.oauth2.pojo.UserInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.sraosha.microservice.oauth2.model.User;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * UserDetails服务实现类
 */
@Slf4j
@Service
@Transactional
public class UserDetailsServiceImpl extends ServiceImpl<UserMapper, User> implements UserDetailsService {

    @Resource
    private ServiceHelper serviceHelper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = serviceHelper.getUserMapper().findUserByUserName(username);
        if (null == user) {
            log.info("用户【】不存在:", user.getUsername());
            return null;
        }

        List<String> roleNameList = serviceHelper.getMapUserRoleMapper().findRoleNameListByUsername(user.getUsername());
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(roleNameList.toArray(new String[roleNameList.size()]));
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setPassword(user.getPassword());
        userInfo.setAuthorities(authorityList);
        return userInfo;
    }
}
